<?php
/**
 * Created by jinqiang on 2025/8/26 9:52.
 * Copyright (c) 2025, Your Company. All rights reserved.
 */


namespace App\Http\Services\Om;


use App\Http\Models\Mysql\SsyProcessingListTable;
use App\Http\Models\Mysql\SsySalesOrderDouyinTable;
use App\Http\Models\Mysql\SsySalesOrderTopTable;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class SalesService
{
    public static function getTable($type)
    {
        switch ($type){
            case "top":
                return (new SsySalesOrderTopTable());
            case "douyin":
                return (new SsySalesOrderDouyinTable());
        }
    }

    public function search($param)
    {
        $conn = self::getTable($param['type']);
        if($param['combine_sku'] ?? ""){
            $conn = $conn->where('combine_sku', $param['combine_sku']);
        }
        if($param['sku'] ?? ""){
            $conn = $conn->where('sku', $param['sku']);
        }
        if($param['date'] ?? []){
            $conn = $conn->whereBetween('order_date', $param['date']);
        }
        $res = $conn->orderBy('order_date', 'desc')->orderBy('id', 'desc')->paginate((Int)$param['limit'])->toArray();
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    public function salesRateStatistic($param)
    {
        $cacheKey = "SALES_STATISTIC_".md5(json_encode($param));
        $salesList = Cache::get($cacheKey) ?: [];
        if(empty($salesList)){
            $salesList = $this->getSalesList($param['type'], $param['order_date']);
            if(empty($salesList)){
                return ['data' => [], 'cache_key' => ""];
            }
            $skus = array_column($salesList, 'sku');
            $processList = (new SsyProcessingListTable())->select('sku_code', DB::raw('sum(num) as total'))->whereBetween('add_date', $param['export_date'])
                ->where('status', 1)->whereIn('sku_code', $skus)->groupBy('sku_code')->get()->toArray();
            $processMap = array_column($processList, 'total', 'sku_code');
            foreach ($salesList as &$item){
                $item['sale_num'] = (Int)$item['sale_num'];
                $item['num'] = (Int)($processMap[$item['sku']] ?? 0);
                $item['rate'] = empty($item['num']) ? 0 : round((Int)$item['sale_num'] / (Int)$item['num'] * 100, 2);
            }
            unset($item);
            $rate = array_column($salesList, 'rate');
            array_multisort($rate, SORT_DESC, $salesList);
            Cache::put($cacheKey, $salesList, Carbon::now()->addMinutes(180));
        }
        return ['data' => $salesList, 'cache_key' => $cacheKey];
    }

    public function getSalesList($type, $orderDate)
    {
        if($type == 'all'){
            $salesList = [];
            foreach (['top', 'douyin'] as $tableType){
                $conn = self::getTable($tableType);
                $list = $conn->select('sku', DB::raw('sum(num) as sale_num'))->whereBetween('order_date', $orderDate)
                    ->groupBy('sku')->get()->toArray();
                $map = array_column($list, null, 'sku');
                foreach ($map as $sku => $item){
                    if(isset($salesList[$sku])){
                        $salesList[$sku]['sale_num'] = $salesList[$sku]['sale_num'] + $item['sale_num'];
                    }else{
                        $salesList[$sku] = $item;
                    }
                }
            }
            return array_values($salesList);
        }else{
            $conn = self::getTable($type);
            $salesList = $conn->select('sku', DB::raw('sum(num) as sale_num'))->whereBetween('order_date', $orderDate)
                ->groupBy('sku')->get()->toArray();
            return $salesList;
        }
    }
}
